import {defineStore} from 'pinia'
import {type RouteState, type TabsMenuProps} from '@/store/interface'
import {type ResMenuList} from '@/api/interface'
import router from '@/router'
import {getAllBreadcrumbList, getFlatArr, getShowMenuList} from '@/utils/utils.ts'

const useRouteStore = defineStore('routeStore', {
	state: (): RouteState => {
		return {
			menuList: [], // 菜单列表
			keepAliveName: [],
			tabsMenuList: []
		}
	},
	getters: {
		getMenuList: state => state.menuList,
		breadcrumbListGet: state => getAllBreadcrumbList(state.menuList),
		flatMenuListGet: state => getFlatArr(state.menuList),
		getShowMenuList: state => getShowMenuList(state.menuList)
	},
	actions: {
		setMenuList(list: ResMenuList[]) {
			this.menuList = list
		},
		setKeepAliveName(nameArr: string[] = []) {
			this.keepAliveName = nameArr
		},
		addKeepAliveName(name: string) {
			!this.keepAliveName.includes(name) && this.keepAliveName.push(name)
		},
		removeKeepAliveName(name: string) {
			this.keepAliveName = this.keepAliveName.filter(item => item !== name)
		},
		removeTabs(tabPath: string, isCurrent: boolean = true) {
			const tabsMenuList = this.tabsMenuList
			if (isCurrent) {
				tabsMenuList.forEach((item, index) => {
					if (item.path !== tabPath) return
					const nextTab = tabsMenuList[index + 1] || tabsMenuList[index - 1]
					if (!nextTab) return
					void router.push(nextTab.path)
				})
			}
			this.tabsMenuList = tabsMenuList.filter(item => item.path !== tabPath)
		},
		setTabs(tabsMenuList: TabsMenuProps[]) {
			this.tabsMenuList = tabsMenuList
		},
		addTabs(tabItem: TabsMenuProps) {
			if (this.tabsMenuList.every(item => item.path !== tabItem.path)) {
				this.tabsMenuList.push(tabItem)
			} else {
				this.tabsMenuList = this.tabsMenuList.map(item => {
					if (item.path === tabItem.path) return tabItem
					return item
				})
			}
		},
		closeMultipleTab(tabsMenuValue?: string) {
			this.tabsMenuList = this.tabsMenuList.filter(item => {
				return item.path === tabsMenuValue || !item.close
			})
		}
	},
	persist: {
		key: 'routeStore',
		storage: sessionStorage
	} // 所有数据持久化
})

export default useRouteStore
